package com.clstu.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPReceiverA {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(9999);//准备在9999端口接收数据
        byte [] buf = new byte[1024];//upd的最大传输单元为64k（即64*1024），现在用不了那么大所以写成1024
                                     //设置缓冲接受
        //构建一个DatagramPacket对象，准备接收数据
        DatagramPacket packet = new DatagramPacket(buf,buf.length);
        System.out.println("接收端A 等待接受数据~~~~~~");

        socket.receive(packet);//接受数据，没有发过来就阻塞（等着）...

        //对收到的packet对象进行拆包
        int length = packet.getLength();
        byte[] data = packet.getData();
        System.out.println(new String(data,0,length));

        //将要发送的信息装到DatagramPacket对象
        data = "好啊，那你请客哦~~~~~~~".getBytes();                            //  指定接收方的ip  ， 端口
        DatagramPacket packet1 = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.1.5"), 9998);
        socket.send(packet1);//发送数据
        //关闭资源
        socket.close();
    }
}
